package com.system.outpatientsystem.service.impl;

import com.system.outpatientsystem.DTO.AppointmentDTO;
import com.system.outpatientsystem.mapper.AppointmentMapper;
import com.system.outpatientsystem.mapper.DoctorMapper;
import com.system.outpatientsystem.pojo.Doctor;
import com.system.outpatientsystem.pojo.appointment_table;
import com.system.outpatientsystem.service.AppointService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class AppointServiceImpl implements AppointService {

    @Autowired
    private AppointmentMapper appointmentMapper;
    @Autowired
    private DoctorMapper doctorMapper;
    @Override
    public void appointment(appointment_table table) {
        appointmentMapper.add(table);
    }

    @Override
    public List<AppointmentDTO> list(Integer userId) {
        List<appointment_table> tablelist = appointmentMapper.list(userId);
        List<AppointmentDTO> dtos = new ArrayList<>();
        for(appointment_table appointmentTable:tablelist){
            AppointmentDTO appointmentDTO=new AppointmentDTO();
            Integer doctorId=appointmentTable.getDoctorId();
            Doctor doctor =doctorMapper.findById(doctorId);
            appointmentDTO.setAppointmentTable(appointmentTable);
            appointmentDTO.setDoctor(doctor);
            dtos.add(appointmentDTO);

        }
        return dtos;

    }

    @Override
    public void deleteAppointment(Integer id) {
        appointmentMapper.deleteById(id);
    }

    @Override
    public AppointmentDTO findById(Integer id) {
        appointment_table appointmentTable= appointmentMapper.findById(id);
        Integer doctorId=appointmentTable.getDoctorId();
        Doctor doctor=doctorMapper.findById(doctorId);
        AppointmentDTO appointmentDTO=new AppointmentDTO();
        appointmentDTO.setAppointmentTable(appointmentTable);
        appointmentDTO.setDoctor(doctor);
        return appointmentDTO;
    }

    @Override
    public boolean lessTwenty(Integer id) {
        appointment_table appointmentTable=appointmentMapper.findById(id);
        LocalDateTime time=appointmentTable.getBeginTime();
        return  isWithin20Minutes(time);
    }
    public  boolean isWithin20Minutes(LocalDateTime targetDateTime) {
        LocalDateTime currentDateTime = LocalDateTime.now();

        // 计算两个时间点之间的时间差
        Duration duration = Duration.between(currentDateTime, targetDateTime);

        // 判断时间差是否小于20分钟
        return duration.toMinutes()< 20;
    }
}
